﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace Lightworks.Core.Entity
{
    public class TreeEntity<T> : BaseEntity
    {
        public long ParentId { get; set; }

        [SugarColumn(IsIgnore = true)]
        public List<T>? Children { get; set; }
    }

    public static class TreeEnityExtensions 
    {
        public static List<T> List2Tree<T>(this List<T> list) where T : TreeEntity<T>
        {
            var lookup = list.ToLookup(n => n.ParentId);
            List<T> result = new List<T>();
            foreach (var item in list) 
            {
                if (item.ParentId == 0) 
                {
                    result.Add(item);
                }
                var children = lookup[item.Id].ToList();
                if (children != null && children.Count > 0)
                {
                    if (item.Children == null)
                        item.Children = new List<T>();
                    children.ForEach(item.Children.Add);
                }

            }
            return result;
        }
        public static List<T> Tree2List<T>(this List<T> list) where T : TreeEntity<T>
        {
            List<T> result = new List<T>();
            void TraverseTree(T node) 
            {
                if (node != null)
                {
                    result.Add(node);
                    if (node.Children == null) 
                        return;
                    foreach (var childNode in node.Children)
                    {
                        TraverseTree(childNode);
                    }
                }
            }
            list.ForEach(x => {
                result.Add(x);
                TraverseTree(x);
            });
            return result;
        }
    }
}
 